// Using a priority_queue // Plus an example of using a function object // Ken Moore 2003 #pragma warning(disable : 4786) #include #include #include #include using namespace std; template class plusk{ private: T sum; public: plusk():sum(0){} void operator()(const T &a){ sum+=a; } T getSum(){return sum;} }; // function object comparator template// templating is optional struct comp{ bool operator()(const T &a,const T &b)const{ // least to greatest return b>a; // greatest to least // return b, comp > pq; // reverse default order //priority_queue,greater > pq; // uses the less function and gives reverse order priority_queue pq; pq.push(987); pq.push(9); pq.push(98742); pq.push(98); while(!pq.empty()) { cout << pq.top() << "\n"; pq.pop(); } // demonstrate the use of a funtion object vector v; v.push_back(100); v.push_back(1); v.push_back(10000); v.push_back(10); //plusk p = for_each(v.begin(),v.end(),plusk()); //cout << p.getSum() << endl; // equivalent to above 2 lines of code cout << for_each(v.begin(),v.end(),plusk()).getSum() << endl; // without for_each ("for_each" is an STL algorithm) vector::iterator it; plusk pk; for(it = v.begin(); it != v.end(); it++) pk(*it); cout << pk.getSum() << endl; }